<template>
    <div class="abnormal-audit">
        <div class="mb-8px">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item
                    :to="item.path"
                    v-for="item in applyInfo.crumbData"
                    :key="item.path"
                    >{{ item.title }}</el-breadcrumb-item
                >
            </el-breadcrumb>
        </div>
        <!-- 基本信息 -->
        <user-info
            @back="goback"
            :fromPath="applyInfo.fromPath"
            :personInfo="applyInfo.personInfo"
            v-if="applyInfo.personInfo"
        ></user-info>
        <!-- 申请明细 -->
        <el-card shadow="never">
            <p class="title">申请明细</p>
            <el-form
                label-position="right"
                label-width="100px"
                :model="applyDetails"
                ref="applyDetails"
            >
                <el-form-item label="内容明细:" class="dashed-line">
                    <div class="border-form">
                        <el-row
                            type="flex"
                            justify="center"
                            align="middle"
                            class="border-bt"
                        >
                            <el-col class="text-right border-rg bg" :span="6"
                                >异动大类:</el-col
                            >
                            <el-col :span="6" class="pd-5px">
                                {{ applyDetails.className }}
                            </el-col>
                            <el-col
                                :span="6"
                                class="text-right border-lf border-rg bg"
                                >异动类型:</el-col
                            >
                            <el-col :span="6" class="pd-5px">
                                {{ applyDetails.typeName }}
                            </el-col>
                        </el-row>
                        <el-row
                            type="flex"
                            justify="center"
                            align="middle"
                            class="border-bt"
                            v-if="applyDetails.reasonName"
                        >
                            <el-col :span="6" class="text-right border-rg bg"
                                >异动原因:</el-col
                            >
                            <el-col :span="18" class="pd-5px">
                                {{ applyDetails.reasonName }}
                            </el-col>
                        </el-row>
                        <el-row
                            type="flex"
                            justify="center"
                            align="middle"
                            v-if="abnormalStartDateTime"
                        >
                            <el-col class="text-right border-rg bg" :span="6"
                                >异动开始时间:</el-col
                            >
                            <el-col :span="6" class="pd-5px">
                                <el-date-picker
                                    v-model="applyDetails.abnormalStartDateTime"
                                    type="date"
                                    value-format="timestamp"
                                    placeholder="选择日期时间"
                                    :disabled="!reviewVisiable"
                                ></el-date-picker>
                            </el-col>
                            <el-col
                                :span="6"
                                class="text-right border-lf border-rg bg"
                                >异动结束时间:</el-col
                            >
                            <el-col :span="6" class="pd-5px">
                                <el-date-picker
                                    v-model="applyDetails.abnormalEndDateTime"
                                    type="date"
                                    value-format="timestamp"
                                    placeholder="选择日期时间"
                                    :disabled="!reviewVisiable"
                                ></el-date-picker>
                            </el-col>
                        </el-row>
                    </div>
                </el-form-item>
                <el-form-item
                    label="异动明细:"
                    class="dashed-line"
                    v-if="applyDetails.detailList.length > 0"
                >
                    <div v-if="$route.query.type == 'review'" class="border-form">
                        <el-row v-for="(fieldItem, index) in abnormalField" :key="index">
                            <template>
                              <template v-if="fieldItem.visiable">
                                <el-form-item style="margin-bottom: 0px;">
                                  <el-col :span="6" class="text-right border-rg bg ">
                                    {{ `${fieldItem.fieldName} :` }}
                                  </el-col>
                                  <el-col :span="7" class="text-left border-rg bg pd-5px">
                                    {{
                                    `${
                                    fieldItem.preValue
                                    ? fieldItem.preValue + ""
                                    : "无"
                                    }`
                                    }}
                                  </el-col>
                                  <el-col :span="1" class="text-center border-rg bg pd-5px">
                                    {{
                                    `改为`
                                    }}
                                  </el-col>
                                   <!-- :disabled="isOperate(fieldItem)"  原本<DictSelect/>组件中 disabled 是由isOperate（）计算得来,偶现不生效情况。
                                     换成fieldItem.ifUpdate 测试偶现问题是否能修复
                                    -->
                                  <el-col :span="10" class="text-left border-rg bg pd-5px">
                                        <DictSelect
                                          v-if="fieldItem.valueType === 'select' && fieldItem.fieldId != 68 && fieldItem.fieldId != 69 && fieldItem.fieldId != 62 && fieldItem.fieldId != 248"
                                          v-model="fieldItem.fieldValue"
                                          @change="selectChange(fieldItem.fieldId)"
                                          :data="fieldItem.options"
                                          :disabled="fieldItem.ifUpdate"
                                          :clearable="false"
                                        ></DictSelect>
                                        <el-select
                                          v-if="fieldItem.fieldId == '68'"
                                          v-model="fieldItem.fieldValue"
                                          filterable
                                          style="width:100%"
                                          :clearable="false"
                                        >
                                          <el-option
                                            v-for="item in options.statusProfession"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value" />
                                        </el-select>
                                        <el-select
                                        v-if="fieldItem.fieldId == '62' || fieldItem.fieldId == '248'"
                                        v-model="fieldItem.fieldValue"
                                        filterable
                                        @change="selectChange(fieldItem.fieldId)"
                                        style="width:100%"
                                        :clearable="false"
                                        >
                                        <el-option
                                        v-for="item in options.facultyList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value" />
                                        </el-select>
                                        <el-select
                                          v-if="fieldItem.fieldId == '69'"
                                          v-model="fieldItem.fieldValue"
                                          style="width:100%"
                                          :clearable="false"
                                        >
                                          <el-option
                                            v-for="item in options.PYZZ"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value" />
                                        </el-select>
                                        <el-input
                                          v-if="fieldItem.valueType === 'input' && fieldItem.fieldId != '77' && fieldItem.fieldId != '78'"
                                          v-model="fieldItem.fieldValue"
                                          :disabled="fieldItem.ifUpdate"
                                          clearable
                                        ></el-input>
                                        <el-select
                                          v-if="fieldItem.fieldId == '77' || fieldItem.fieldId == '78'"
                                          v-model="fieldItem.fieldValue"
                                          :remote-method="getTeacher"
                                          filterable
                                          remote
                                          :clearable="false"
                                          style="width:100%"
                                          @input="testClick">
                                          <el-option
                                            v-for="item in options.teachersList"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value" />
                                        </el-select>
                                        <template v-if="fieldItem.valueType == 'date' ">
                                          <DictSelect
                                            v-if="fieldItem.fieldValueType === 'select' && fieldItem.fieldId != '76' && fieldItem.fieldId != '83' && fieldItem.fieldId != '75'"
                                            v-model="fieldItem.fieldValue"
                                            :disabled="fieldItem.ifUpdate"
                                            :data="options.changeType"
                                            :clearable="false"
                                          ></DictSelect>
                                          <DictSelect
                                            v-if="fieldItem.fieldId == '92'"
                                            :disabled="fieldItem.ifUpdate"
                                            v-model="fieldItem.fieldValue"
                                            :data="options.changeDate"
                                            :clearable="true" />
                                          <DictSelect
                                            v-if="fieldItem.fieldId == '83' && fieldItem.fieldValueType === 'select'"
                                            :disabled="fieldItem.ifUpdate"
                                            v-model="fieldItem.fieldValue"
                                            :data="options.studyDate"
                                            :clearable="true" />
                                          <el-date-picker
                                            v-if="(fieldItem.fieldValueType === 'int') && fieldItem.fieldId != '92' && fieldItem.fieldId != '83'"
                                            v-model="fieldItem.fieldValue"
                                            :disabled="fieldItem.ifUpdate"
                                            type="date"
                                            style="width:100%"
                                            placeholder="选择日期"
                                          ></el-date-picker>
                                        </template>
                                        <el-date-picker
                                          v-if="(fieldItem.valueType == 'year' || fieldItem.fieldId == '83') && fieldItem.fieldValueType === 'int'"
                                          :disabled="fieldItem.ifUpdate"
                                          v-model="fieldItem.fieldValue"
                                          type="year"
                                          style="width:100%"
                                          placeholder="选择年级"
                                          @change="selectChange(fieldItem.fieldId)"
                                          value-format="yyyy"
                                        ></el-date-picker>
                                        <DictSelect
                                          v-if="(fieldItem.fieldId == '76' || fieldItem.fieldId == '75') &&  fieldItem.fieldValueType === 'select'"
                                          :disabled="fieldItem.ifUpdate"
                                          v-model="fieldItem.fieldValue"
                                          :data="options.comeGrade"
                                          :clearable="true" />
                                  </el-col>
                                </el-form-item>
                              </template>
                            </template>
                        </el-row>
                    </div>
                    <div v-if="$route.query.type == 'view'" class="border-form">
                        <el-row
                            type="flex"
                            justify="center"
                            align="middle"
                            class="border-bt"
                            v-for="(item, index) in applyDetails.detailList"
                            :key="index"
                        >
                            <el-col :span="6" class="text-right border-rg bg">
                               {{ `${item.label}:` }}
                            </el-col>
                            <el-col :span="18">
                                {{
                                    `${
                                        item.preValue
                                            ? item.preValue + ""
                                            : "无"
                                    }改为${
                                        item.currentValue
                                            ? item.currentValue + ""
                                            : "无"
                                    }`
                                }}
                            </el-col>
                        </el-row>
                    </div>
                </el-form-item>
                <el-form-item
                    label="OA文号:"
                    v-if="
                        !!(applyInfo.personInfo.oaNumb * 1) && !reviewVisiable
                    "
                >
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-input
                                disabled
                                type="input"
                                :rows="4"
                                resize="none"
                                v-model="applyInfo.personInfo.oaWH"
                                maxlength="500"
                            ></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="原因说明:" v-if="!!applyDetails.remark">
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-input
                                disabled
                                v-model="applyDetails.remark"
                                type="textarea"
                                :rows="4"
                                resize="none"
                                maxlength="2000"
                            ></el-input>
                        </el-col>
                        <el-col :span="8">(限长2000个字)</el-col>
                    </el-row>
                </el-form-item>

                <el-form-item
                    label="代理理由:"
                    v-if="!!applyDetails.proxyReason"
                >
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-input
                                disabled
                                v-model="applyDetails.proxyReason"
                                type="textarea"
                                :rows="4"
                                resize="none"
                                maxlength="2000"
                            ></el-input>
                        </el-col>
                        <el-col :span="8">(限长2000个字)</el-col>
                    </el-row>
                </el-form-item>
                <el-form-item
                    label="申请材料:"
                    v-if="!!applyDetails.attachFile"
                >
                    <!-- <el-button
                    type="text"
                    v-for="item in applyDetails.attachFile"
                    :key="item.url"
                    @click="download(item)">
                    {{ item.name }}
                    </el-button> -->
                    <PreviewOffice
                    :newFileList="applyDetails.attachFile"
                    />
                </el-form-item>
                
            </el-form>
        </el-card>
        <!-- 审核 -->
        <el-card shadow="never" v-if="reviewVisiable">
            <p class="title">审核</p>
            <el-form
                label-position="rigth"
                label-width="100px"
                ref="auditForm"
                :model="auditForm"
                :rules="auditRules"
            >
              <div v-show="showIf">
                <el-form-item
                    label="OA文号:"
                    v-if="!!(applyInfo.personInfo.oaNumb * 1)"
                >
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-input
                                type="input"
                                :rows="4"
                                resize="none"
                                v-model="approvalInfo.oaWH"
                                maxlength="500"
                            ></el-input>
                        </el-col>
                    </el-row>
                </el-form-item>
              </div>
                <el-form-item label="审批意见:">
                    <el-row :gutter="16">
                        <el-col :span="8">
                            <el-input
                                type="textarea"
                                :rows="4"
                                resize="none"
                                v-model="approvalInfo.content"
                                maxlength="2000"
                            ></el-input>
                        </el-col>
                        <el-col :span="8">(限长2000个字)</el-col>
                    </el-row>
                </el-form-item>
            </el-form>
            <div class="btnGroup text-right">
                <el-button type="danger" @click="handleClick()">驳回</el-button>
                <el-button type="primary" @click="handleClick(1)"
                    >通过</el-button
                >
            </div>
        </el-card>
        <!-- 审批进度 -->
        <el-card
            shadow="never"
            v-if="this.applyInfo.personInfo.workflowNo && this.applyInfo.personInfo.workflowNo.length > 1"
        >
            <p class="title">审批进度</p>
            <edu-table
                :order="false"
                :pagination="false"
                :selection="false"
                :data="auditList"
            >
                <el-table-column label="序号">
                    <template slot-scope="scope">{{ scope.row.id }}</template>
                </el-table-column>
                <el-table-column label="时间">
                    <template slot-scope="scope">
                        {{ scope.row.time | formatDate }}
                    </template>
                </el-table-column>
                <el-table-column
                    label="审批人"
                    prop="approvorName"
                ></el-table-column>
                <el-table-column
                    label="角色"
                    prop="approvorRole"
                ></el-table-column>
                <el-table-column label="审批结果" prop="result" width="120">
                    <template slot-scope="scope">
                        <el-tag
                            v-if="scope.row.result == 'Submit'"
                            type="success"
                            >提交</el-tag
                        >
                        <el-tag
                            v-if="scope.row.result == 'Process'"
                            type="success"
                            >已审核</el-tag
                        >
                        <el-tag v-if="scope.row.result == 'End'" type="success"
                            >已通过</el-tag
                        >
                        <el-tag
                            v-if="scope.row.result == 'Reject'"
                            type="warning"
                            >已驳回</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    label="审批节点"
                    prop="setpId"
                ></el-table-column>
                <el-table-column
                    label="审批说明"
                    prop="content"
                    show-overflow-tooltip
                ></el-table-column>
            </edu-table>
        </el-card>
        <el-dialog
            title="图片预览"
            :visible.sync="picDialogVisible"
            :show-close="false"
            width="50%">
            <img :src="'api/commonservice/obsfile/downloadfile?objectkey=' + picUrl" alt="" width="100%">
            <span slot="footer" class="dialog-footer">
                <el-button @click="picDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="download(picUrl, 'pic')">下载</el-button>
            </span>
        </el-dialog>
        <el-dialog title="申请此类异动需完成以下所有课程的退课，是否确定" :visible.sync="dialogTableVisible" width="900px">
        <el-table :data="gridData" style="margin-bottom: 30px">
            <el-table-column type="index"   label="序号" width="100"></el-table-column>
                <el-table-column property="studentId" label="学号" width="150"></el-table-column>
                <el-table-column property="name" label="姓名" width="150"></el-table-column>
            <el-table-column property="courseCode" label="课程序号" width="200"></el-table-column>
            <el-table-column property="courseName" label="课程名称" width="200"></el-table-column>
        </el-table>
        <div style="height: 25px;">
            <el-button type="primary" style="float:right;"   @click="auditPass()">确定</el-button>
            <el-button type="primary" style="float:right; margin-right:20px" @click="cancel()">取消</el-button>
        </div>
        </el-dialog>
    </div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import { findTeacherList } from 'common/src/api/culture/change';
import * as API from "common/src/api/abnormalType/abnormal";
import * as applyApi from "common/src/api/studentStatus/abnormalToApply";
import userInfo from "./components/userInfo";
import { findStatusProfessionList, allFacultyList } from 'common/src/api/studentinfo'
import PreviewOffice from "common/src/components/common/PreviewOffice.vue"
import {
    selectApproFlow,
    approvalThrough,
    approvalReject
} from "common/src/api/approval";

import filters from "common/src/filters";
import moment from "moment";
import mixin from 'common/src/mixins/index';
export default {
    name: "abnormalAudit",
    mixins: [mixin],
    components: {
        userInfo,
        PreviewOffice
    },
    filters: {
        formatDate(date) {
            return filters.formatDate(date, "yyyy/MM/dd hh:mm:ss");
        }
    },
    data() {
        return {
            showIf: true,
            dialogTableVisible: false,
            gridData: [],
            majorDirectionName: '',
            majorDirectionCode: '',
            abnormalField: [],
            abnormalField_: [],
            applyInfo: {
                crumbData: [],
                fromPath: "",
                personInfo: ""
            },
            xy: '',
            nj: '',
            applyDetails: {
                classId: '',
                remark: "",
                proxyReason: "",
                attachFile: [],
                className: "",
                typeName: "",
                reasonName: "",
                abnormalStartDateTime: "",
                abnormalEndDateTime: "",
                detailList: []
            },
            approvalInfo: {
                uid: "",
                no: "",
                content: "",
                approveAttachment: [],
                oaWH: ""
            },
            professionParm: {
                grade: '', // 当前年级
                statusFacultyList: [], // 学院
            },
            dicParm: {
                degreeType: '', // 学位类型
                grade: '', // 当前年级
                trainingLevel: '', // 培养层次
                facultys: [] // 学院
            },
            options: {
                abnormalCategories: [],
                abnormalType: [],
                teachersList: [],
                statusProfession:[],
                abnormalReason: [],
                PYZZ: [],
                changeType: [
                    {
                        value: '0',
                        label: '异动生效时间'
                    },
                    {
                        value: '1',
                        label: '审批通过时间'
                    }
                ],
                changeDate: [],
                comeGrade: [],
                studyDate: [],
                facultyList: [] // 所有学院
            },
            projectId: '',
            auditList: [],
            auditForm: {},
            auditRules: {},
            reviewVisiable: true, //控制审核模块的显示
            picDialogVisible: false,
            picUrl: '',
            picName: ''
        };
    },
    created() {
        this.projectId = this.global.projectId;
        this.getApplyInfo();
        this.getAbnormalDetails();
        this.getVal();
        this.getFacultyList()
        // console.log(this.applyInfo.crumbData, '1');
        // console.log(this.reviewVisiable, '2');
        // console.log(this.applyInfo.personInfo, '3');
        const user = this.mockUser ? this.mockUser : this.currentUser;
        /*debugger*/
        if (user.currentRole === '1' && user.innerRoles[0] === '1' && (user.innerRoles.length > 1 ? user.innerRoles[1] !== '2' : user.innerRoles)) {
            this.showIf = true;
        }else {
            this.showIf = false;
        }
    },
    methods: {
        // 拼装审批信息
        async getApplyInfo() {
            let queryParams = this.$route.query;
            this.applyDetails.remark = queryParams.studentInfo.remark;
            this.applyDetails.proxyReason = queryParams.studentInfo.proxyReason;
            this.applyDetails.attachFile = JSON.parse(
                queryParams.studentInfo.attachFile
            );
            this.approvalInfo.oaWH = queryParams.studentInfo.oaWH;
            if (String(queryParams.reviewVisiable) !== "undefined")
                this.reviewVisiable = queryParams.reviewVisiable;
            let crumbData = null;

            if (queryParams && queryParams.type === "view") {
                if(queryParams.comePage === "changeDueList") {
                    crumbData = [
                        {
                            path: "/changeDueList",
                            title: "异动到期名单"
                        },
                        {
                            title: "详情查看"
                        }
                    ];
                    this.applyInfo = {
                        crumbData: crumbData,
                        fromPath: "/changeDueList",
                        personInfo: queryParams.studentInfo
                    };

                } else {
                    crumbData = [
                        {
                            path: "/abnormalManage",
                            title: "学籍异动管理"
                        },
                        {
                            title: "详情查看"
                        }
                    ];
                    this.applyInfo = {
                        crumbData: crumbData,
                        fromPath: "/abnormalManage",
                        personInfo: queryParams.studentInfo
                    };
                }
                
            } else if (queryParams && queryParams.type === "review") {
                crumbData = [
                    {
                        path: "/abnormalManage",
                        title: "学籍异动管理"
                    },
                    {
                        title: "异动审核"
                    }
                ];
                this.applyInfo = {
                    crumbData: crumbData,
                    fromPath: "/abnormalManage",
                    personInfo: queryParams.studentInfo
                };
            }
            this.applyInfo.personInfo.workflowNo && this.applyInfo.personInfo.workflowNo.length > 1 &&
                this.getDetails(this.applyInfo.personInfo.workflowNo);
        },
        // 返回上一级
        goback() {
            this.$store.commit("delete_tabs", this.$route.path);
            if(this.$route.query.type === 'view' || 'review') {
                if(this.$route.query.comePage === "changeDueList") {
                    this.$router.push({
                        path: "/changeDueList",
                        query: {
                             type: 'view',
                        }
                    });

                } else {
                    this.$router.push({
                        path: "/abnormalManage",
                        query: {
                             type: 'view',
                             routerQuery: JSON.stringify(this.$route.query.routerQuery),
                             extralQuery: JSON.stringify(this.$route.query.extralQuery),
                        }
                    });
                }
            } else {
                this.$router.go(-1);
            }

        },
        // 获取导师1/2下拉数据
        getTeacher(e) {
            findTeacherList({ keyWord: e }).then(res => {
                if (res.code == 200) {
                    this.options.teachersList = [];
                    let opts = [];
                    opts = res.data.map((item) => {
                        return {
                            label: item.name + '(' + item.code + ')',
                            value: item.code
                        };
                    });
                    this.options.teachersList = opts;
                } else {
                   throw res.code;
                }
            });
        },
        // 获取所有学院
        getFacultyList() {
            this.options.facultyList = []
            allFacultyList().then(res=> {
                if(res.code === 200 && res.data) {
                    res.data.forEach(faculty=> {
                        this.options.facultyList.push({
                        label: faculty.deptName,
                        value: faculty.deptCode
                        })
                    })
                }
            })
        },
        getVal() {
            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: ['X_YD_YJBYSJ','X_YD_RXSJ','X_YD_RXNJ']
            };
            // 获取学籍状态和培养层次数据字典信息，用于在页面中显示异动类型信息
            queryDic(data).then(res => {
                if (res.code === 200) {
                    UTILS.fillSelect(
                        {
                            changeDate: 'X_YD_YJBYSJ',
                            comeGrade: 'X_YD_RXNJ',
                            studyDate: 'X_YD_RXSJ'
                        },
                        res.data,
                        this.options
                    );
                    // 这时需要根据异动大类的code查询该大类下面所有异动类型
                }
            });
        },
        // 获取变更字段下拉数据
        async getFieldOptions(val) {
            let params = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: [val.value],
                filter: {
                    facultys: [this.xy],
                    grade: this.nj
                }
            };
            if (val.value === 'G_ZY') {
               this.tempVal = val.fieldValue
            }
            if (val.value === 'X_FX') {
                queryZYFX(this.tempVal).then(res => {
                    // console.log(res)
                    UTILS.fillSelect(
                        {
                            options: val.value
                        },
                        res.data,
                        val
                    )
                })
            } else {
                let { data, code } = await queryDic(params);
                if (code !== 200) return;
                UTILS.fillSelect(
                    {
                        options: val.value
                    },
                    data,
                    val
                )
            }

            return val
        },
        // 获取学籍专业
        getProfessionList() {
            this.options.statusProfession = [];
            findStatusProfessionList(this.professionParm).then(resT=> {
                if(resT.code === 200) {
                    resT.data.forEach(val=> {
                        this.options.statusProfession.push(
                            {
                                label: val.professionName + '(' + val.professionCode + ')',
                                value: val.statusProfessionCode
                            }
                        )
                    })
                }
            })
        },
        // 获取培养专业
        async getPyzy(keys) {
            const data = {
                filter: {
                  /*degreeType: ['1'],*/
                  /*grade: 2020,*/
                },
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys:['G_ZY']
            };
            this.options.PYZZ = [];

            for (let i = 0; i < this.abnormalField.length; i++) {

              if (this.abnormalField[i].fieldId == 62) {
                data.filter.facultys = [this.abnormalField[i].fieldValue];
              }
              if (this.abnormalField[i].fieldId == 76 && this.projectId == 1) {
                data.filter.grade = this.abnormalField[i].fieldValue;
              }
              if (this.abnormalField[i].fieldId == 96 && this.projectId == 2) {
                data.filter.degreeType = this.abnormalField[i].fieldValue;
              }
              if (this.abnormalField[i].fieldId == 72 && this.projectId == 2) {
                data.filter.trainingLevel = this.abnormalField[i].fieldValue;
              }
            }
            return await queryDic(data);
        },
        // 获取申请详情
        async getDetails(id) {
            try {
                const res = await selectApproFlow(id);
                if (res.code === 200 && res.data) {
                    let cont = res.data.content
                        ? JSON.parse(res.data.content)
                        : {};
                    if (cont) {
                        //保存审核参数
                        this.approvalInfo.uid = res.data.applicantId;
                        this.approvalInfo.no = res.data.no;
                    }
                }
                const { code, data } = await API.selectApproveHistory(id);
                if (code == 200) this.auditList = data ? data : [];
            } catch (err) {
                console.log(err);
            }
        },
        async getFieldAuth(val) {
            try {
                this.abnormalField = [];
                let formData = null;
                if (!Array.isArray(this.applyInfo.personInfo)) {
                    formData = JSON.parse(this.applyInfo.personInfo.formData)
                }
                let { code, data } = await applyApi.getFieldAuth(val);
                if (code === 200 && data) {
                    let global = this.$store.getters.getGlobal()
                    data.map(item => {
                        if (item.fieldId === '62') {
                            this.xy = item.fieldValue
                        }
                        if (item.fieldId === '76') {
                           this.nj = item.fieldValue
                        }
                        if (item.fieldId === '70') {
                           item.value = 'X_FX'
                        }
                        if (item.fieldId === '92') {
                            item.value = 'X_YD_YJBYSJ'
                        }
                        if (formData) {
                            item.fieldValue = formData[item.fieldId] ? formData[item.fieldId] : ''
                        }
                        // console.log(item.value)
                        if (item.value) {
                            item.options = [];
                            item = this.getFieldOptions(item)
                        }
                        if (item.fieldId === '77' || item.fieldId === '78') {
                            this.getTeacher(item.fieldValue)
                        }

                        if(global.isStudent && item.studentUpdate == 1) {
                            item.ifUpdate = false
                        } else if(global.isAcdemicDean && item.facultyUpdate == 1) {
                            item.ifUpdate = false
                        } else if(global.isAdmin && item.collegeUpdate == 1) {
                            item.ifUpdate = false
                        }

                        return item
                    });
                    let flag = 0; // 判断学籍专业是否拉数据
                    let bksopt = 0; // 判断本科生培养专业是否拉数据
                    let yysopt = 0; // 判断研究生培养专业是否拉数据
                    this.abnormalField = data;
                    if(data) {
                        // 学籍专业下拉框赋值
                        data.forEach(val=> {
                            if(val.fieldId == 76 && val.fieldValue) {
                                // 当前年级
                                flag = flag + 1;
                                bksopt = bksopt + 1;
                                this.professionParm.grade = val.fieldValue
                            }
                            if(val.fieldId == 248 && val.fieldValue) {
                                // 学籍学院
                                flag = flag + 1;
                                this.professionParm.statusFacultyList.push(val.fieldValue)
                            }
                            if(val.fieldId == 62 && val.fieldValue) {
                                // 学院
                                bksopt = bksopt + 1;
                                yysopt = yysopt + 1
                            }
                            if(val.fieldId == 72 && val.fieldValue) {
                                // 培养层次
                                yysopt = yysopt + 1
                            }
                            if(val.fieldId == 96 && val.fieldValue) {
                                // 学位类型
                                yysopt = yysopt + 1
                            }
                        })
                    }

                    if(this.projectId == 1 && flag === 2) {
                        this.getProfessionList()
                    }
                    if(this.projectId == 1 && bksopt === 2) {
                        this.getPyzy().then(res=> {
                            if(res.code === 200 && res.data) {
                                for(let key in res.data.G_ZY) {
                                    this.options.PYZZ.push({
                                        label: res.data.G_ZY[key],
                                        value: key
                                    })
                                }
                            }
                        })
                    }
                        if(this.projectId == 2 && yysopt === 3) {
                            this.getPyzy().then(res=> {
                                if(res.code === 200 && res.data) {
                                    for(let key in res.data.G_ZY) {
                                        this.options.PYZZ.push({
                                            label: res.data.G_ZY[key],
                                            value: key
                                        })
                                    }
                                }
                            })
                        }
                        this.selectChange();
                        //将学生异动的原始值、修改后的值加入到明细中
                        this.abnormalField.forEach(val=> {
                            for (let key in this.applyDetails.detailList) {
                                let value = this.applyDetails.detailList[key];
                                if(val.fieldName === value.label) {
                                    val.preValue = value.preValue;
                                    break;
                                }
                            }
                            for (let key in this.applyDetails.logFormData) {
                                let value = this.applyDetails.logFormData[key];
                                if(val.fieldName === value.keyValue) {
                                    val.fieldValue = value.code;
                                    break;
                                }
                            }
                        });
                        this.abnormalField_ = _.cloneDeep(this.abnormalField);
                }
            } catch (err) {
                console.log(err)
            }
        },
        selectChange(val) {
            //申请转入学院时，写入faculty参数
            if (this.applyDetails.classId == '300006') {
                let obj = this.abnormalField.find(a => a.fieldId * 1 == 62 && a.fieldName == '学院');
                let code = obj ? obj.fieldValue : '';
                let params = this.applyInfo.personInfo;
                if (Array.isArray(params)) {
                    params.forEach(p => (p.faculty = code))
                } else {
                    params.faculty = code
                }
                this.$set(this.applyInfo, 'personInfo', params)
            }
            for(let i = 0; i < this.abnormalField.length; i++) {
                if(this.abnormalField[i].fieldId == 96) {
                    // 学位类型
                    this.dicParm.degreeType = this.abnormalField[i].fieldValue
                }
                if(this.abnormalField[i].fieldId == 72) {
                    // 培养层次
                    this.dicParm.trainingLevel = this.abnormalField[i].fieldValue
                }
                if(this.abnormalField[i].fieldId == 62) {
                    // 学院
                    this.dicParm.facultys.push(this.abnormalField[i].fieldValue)
                }
                if(this.abnormalField[i].fieldId == 248) {
                    // 学籍学院
                    this.professionParm.statusFacultyList = [];
                    this.professionParm.statusFacultyList.push(this.abnormalField[i].fieldValue)
                }
                if(this.abnormalField[i].fieldId == 76) {
                    // 当前年级
                    this.professionParm.grade = this.abnormalField[i].fieldValue;
                    this.dicParm.grade = this.abnormalField[i].fieldValue
                }

            }
            if(this.projectId == 1 && (val == 76 || val == 248)) {
                this.abnormalField.forEach(val=> {
                    if(val.fieldId == 68) {
                        val.fieldValue = ''
                        // 置空学籍专业
                    }
                });
                this.getProfessionList()
            }
            if(this.projectId == 2 && (val == 72 || val == 62 || val == 96)) {
                this.abnormalField.forEach(val=> {
                    if(val.fieldId == 69) {
                        val.fieldValue = ''
                        // 置空学籍专业
                    }
                });
                if(this.dicParm.grade && this.dicParm.facultys && this.dicParm.degreeType) {
                    this.getPyzy().then(res=> {
                        if(res.code === 200 && res.data) {
                            for(let key in res.data.G_ZY) {
                                this.options.PYZZ.push({
                                    label: res.data.G_ZY[key],
                                    value: key
                                })
                            }
                        }
                    })
                }
            }
            if(this.projectId == 1 && (val == 76 || val == 62)) {
                this.abnormalField.forEach(val=> {
                    if(val.fieldId == 69) {
                        val.fieldValue = ''
                        // 置空学籍专业
                    }
                });
                if(this.dicParm.grade && this.dicParm.facultys) {
                    this.getPyzy().then(res=> {
                        if(res.code === 200 && res.data) {
                            for(let key in res.data.G_ZY) {
                                this.options.PYZZ.push({
                                    label: res.data.G_ZY[key],
                                    value: key
                                })
                            }
                        }
                    })
                }
            }
        },
        async getAbnormalDetails() {
            let data = {
                classId: this.applyInfo.personInfo.classId,
                typeCode: this.applyInfo.personInfo.typeCode,
                reasonId: this.applyInfo.personInfo.reasonId,
                studentId: this.applyInfo.personInfo.studentId,
                id: this.applyInfo.personInfo.id
            };
            applyApi.queryAbnormalApply(data).then(res => {
                if (res.code === 200 && res.data) {
                    if (res.data.abnormalDetailList) {
                        let detailList = JSON.parse(
                            res.data.abnormalDetailList
                        );
                        detailList.forEach(e => {
                            if (e.label && e.label.includes("时间")) {
                                (e.preValue = e.preValue.split(" ")[0]),
                                    (e.currentValue = e.currentValue.split(
                                        " "
                                    )[0]);
                            }
                        });
                        this.applyDetails.detailList =
                            detailList.length > 0 && detailList;

                        //获取异动的字段权限
                        if(this.$route.query.type == 'review'){
                            this.getFieldAuth(this.applyInfo.personInfo.typeCode);
                        }

                    }
                    this.$set(this.applyDetails, "typeName", res.data.typeName);
                    this.$set(
                        this.applyDetails,
                        "reasonName",
                        res.data.reasonName
                    );
                    this.$set(
                        this.applyDetails,
                        "classId",
                        res.data.classId
                    );
                    this.$set(
                        this.applyDetails,
                        "className",
                        res.data.classIdI18n
                    );
                    let startTime = new Date(
                        res.data.abnormalStartDateTime
                    ).getTime();
                    let endTime = new Date(
                        res.data.abnormalEndDateTime
                    ).getTime();
                    this.$set(
                        this.applyDetails,
                        "abnormalStartDateTime",
                        startTime
                    );
                    this.abnormalStartDateTime = _.cloneDeep(startTime);
                    this.$set(
                        this.applyDetails,
                        "abnormalEndDateTime",
                        endTime
                    );
                    this.abnormalEndDateTime = _.cloneDeep(endTime);
                }
            });
        },
        /**
         * 返回、提交按钮点击
         * params {tpye} 不传->驳回，1->通过
         */
        async handleClick(type = "") {
            try {
                // if (
                //     !!(this.applyInfo.personInfo.oaNumb * 1) &&
                //     !!this.approvalInfo.oaWH
                // ) {
                //     if (!this.testOa(this.approvalInfo.oaWH)) {
                //         this.$message({
                //             type: "warning",
                //             message: "OA文号必须是数字+字母组合"
                //         });
                //         return;
                //     }
                // }
                if (!type) {
                    if (!this.approvalInfo.content) {
                        this.$message({
                            type: "warning",
                            message: "请先填写驳回意见"
                        });
                        return;
                    }
                    
                    const res = await approvalReject(
                        Object.assign(this.approvalInfo, {
                            oaNo: this.approvalInfo.oaWH
                        })
                    );
                    if (res.code == 200) this.goback();
                } else {
                    // 学籍状态 等于4：休学，6：退学，21：保留学籍 需要先退课
                    let flag = false
                    if(this.projectId != 1 && this.abnormalField && this.abnormalField.length > 0) {
                        this.abnormalField.forEach(deta=> {
                            if(deta.fieldId == "101" && (deta.fieldValue == 4 || deta.fieldValue == 6 || deta.fieldValue == 21)) {
                                flag = true
                            }
                        })
                    }
                    if(flag) {
                        this.gridData = [];
                        let parm = [
                            {
                                studentId: this.applyInfo.personInfo.studentId,
                                abnormalStartTimeFormart: this.applyInfo.personInfo.abnormalStartTimeFormart,
                            }
                        ];
                        applyApi.coursesInAbnormalTime(parm).then(res=> {
                            if(res.code === 200 && res.data) {
                                this.dialogTableVisible = true;
                                    res.data.forEach(val=> {
                                        this.gridData.push({
                                        name: this.applyInfo.personInfo.studentName,
                                        studentId: this.applyInfo.personInfo.studentId,
                                        courseName: val.courseName,
                                        courseCode: val.courseCode
                                    })
                                })
                            }
                        })
                    } else {
                        this.dialogTableVisible = false;
                        this.gridData = [];
                        this.auditPass()
                    }
                }
            } catch (err) {
                console.log(err);
            }
        },
        cancel() {
            this.dialogTableVisible = false;
            this.gridData = []

        },
        async auditPass() {
            if (
                    this.abnormalStartDateTime !==
                        this.applyDetails.abnormalStartDateTime ||
                    this.abnormalEndDateTime !==
                        this.applyDetails.abnormalEndDateTime
                ) {
                    await API.updateAbnormalTime({
                        abnormalStartTime: this.applyDetails
                            .abnormalStartDateTime,
                        abnormalEndTime: this.applyDetails
                            .abnormalEndDateTime,
                        studentId: this.applyInfo.personInfo.studentId,
                        id: this.applyInfo.personInfo.id
                    });
                }

            //审核页面通过前判断是否修改异动详情字段，如果修改先保存修改内容
            if(this.$route.query.type == 'review') {
                let isChange = false;
                for (let k in this.abnormalField_){
                    let val = this.abnormalField_[k];
                    for (let key in this.abnormalField) {
                        let value = this.abnormalField[key];
                        if(val.fieldName === value.fieldName) {
                            if(val.fieldValue != value.fieldValue) {
                                isChange = true;
                            }
                            break;
                        }
                    }
                    if(isChange){
                        break;
                    }
                }

                if(isChange) {
                    this.updateAbnormalField();
                } else {
                    const res = await approvalThrough(
                        Object.assign(this.approvalInfo, {
                            oaNo: this.approvalInfo.oaWH
                        })
                    );
                    if (res.code == 200) this.goback();
                }
            } else {
                const res = await approvalThrough(
                    Object.assign(this.approvalInfo, {
                        oaNo: this.approvalInfo.oaWH
                    })
                );
                if (res.code == 200) this.goback();
            }
        },
        async updateAbnormalField() {
            let obj = {};
            let formData = '';
            let logFormData = [];
            this.abnormalField.forEach(item => {
                if (item['required']) {
                    if (!item.fieldValue) {
                        this.$message({
                            type: 'warning',
                            message: `${item.fieldName}是必填项`
                        });
                        throw 'err'
                    }
                }
                obj[item.fieldId] = item.fieldValue


            });
            formData = JSON.stringify(obj);
            let json = JSON.parse(formData);

            for (let i = 0; i < this.abnormalField.length; i++) {
                if (this.abnormalField[i].fieldId === '70') {
                    this.majorDirectionCode = this.abnormalField[i].fieldValue;
                    for (let j = 0; j < this.abnormalField[i].options.length; j++) {
                        if (
                            this.abnormalField[i].options[j].key === this.majorDirectionCode
                        )
                            /*alert(this.abnormalField.options[j].label);*/
                            this.majorDirectionName = this.abnormalField[i].options[j].label
                    }
                }
            }

            this.abnormalField.forEach(e => {
                let code = '';
                let value = '';
                let lsValueKey = '';

                if(e.fieldValue && this.options.changeDate) {
                    this.options.changeDate.forEach(val=> {
                        if(val.value === e.fieldValue) {
                            lsValueKey = val.label;
                        }
                    })
                }

                let lsComeGrade = '';
                if(e.fieldValue && this.options.comeGrade) {
                    this.options.comeGrade.forEach(val=> {
                        if(val.value === e.fieldValue) {
                           lsComeGrade = val.label;
                        }
                    })
                }

                let lsStudyDate = '';
                if(e.fieldValue && this.options.studyDate) {
                    this.options.studyDate.forEach(val=> {
                        if(val.value === e.fieldValue) {
                           lsStudyDate = val.label;
                        }
                    })
                }

                if (e.valueType == 'input') {
                    value = e.fieldValue;
                } else if (e.valueType == 'select') {
                    if (e.fieldId == '68') {
                        let xjObj = this.options.statusProfession.find(o => o.value == e.fieldValue);
                        code = e.fieldValue;
                        value = xjObj ? xjObj.label.substring(0,(xjObj.label).lastIndexOf('(')) : '';
                    }
                    if (e.fieldId == '62' || e.fieldId == '248') {
                        let faculty = this.options.facultyList.find(o => o.value == e.fieldValue);
                        code = e.fieldValue;
                        value = faculty ? faculty.label : '';
                    }
                    if (e.options && e.fieldId != '68' && e.fieldId != '69' && e.fieldId != '62' && e.fieldId != '248') {
                        let obj = e.options.find(o => o.value == e.fieldValue);
                        code = e.fieldValue;
                        value = obj ? obj.label : '';
                    }
                    if (this.options && this.options.PYZZ && e.fieldId == '69') {
                        let obj = this.options.PYZZ.find(o => o.value == e.fieldValue);
                        code = e.fieldValue;
                        value = obj ? obj.label : '';
                    }
                } else if (e.valueType == 'date') {
                    let keyTime = e.fieldValue;
                    if (e.fieldId == '93' || e.fieldId == '110') {
                        // value = UIndex.parseTime(e.fieldValue, '{y}-{m}-{d}')
                        if(e.fieldValue && e.fieldValue.length !== 1) {
                            value = moment(e.fieldValue).format('YYYY-MM-DD');
                        } else if(e.fieldValue.length === 1) {
                            value = keyTime == '0' ? '异动生效时间' : '审核通过时间';
                        }else {
                            value = "";
                        }
                    } else if (keyTime.constructor === String) {
                        if (keyTime.length === 1 && !lsStudyDate) {
                            value = keyTime == '0' ? '异动生效时间' : '审核通过时间';
                        } else if(lsValueKey) {
                            value = lsValueKey;
                        }else if(lsStudyDate) {
                            value = lsStudyDate;
                        }
                        else {
                            value = keyTime;
                        }
                    }
                } else if (e.valueType == 'year') {
                    if(lsComeGrade) {
                       value = lsComeGrade
                    } else {
                       value = e.fieldValue
                    }
                }

                logFormData.push({
                    key: e.fieldId,
                    keyValue: e.fieldName,
                    code: code,
                    value: value,
                    dictCode: e.value ? e.value : ''
                })

            });

            for (let U = 0; U < logFormData.length; U++) {
                if (logFormData[U].key === '83' && json[83].length >= 10) {
                    logFormData[U].value = json[83].substring(0, 10);
                }
                if (logFormData[U].key === '92' && json[92].length >= 10) {
                    logFormData[U].value = json[92].substring(0, 10);
                }
            }

            let params = {
                content: {
                    formData: formData,
                    id: this.applyInfo.personInfo.id,
                    studentId: this.applyInfo.personInfo.studentId,
                    abnormalDetailList: logFormData
                }
            };
            await API.approveSave(params).then(res=> {
                if (res.code == 200) {
                    approvalThrough(
                        Object.assign(this.approvalInfo, {
                            oaNo: this.approvalInfo.oaWH
                        })
                    ).then(r=> {
                        if (r.code == 200) this.goback();
                    });

                }
            });
        },
        testOa(str) {
            return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{2,100}$/.test(str);
        },
        download(params, type) {
            if (type === 'pic') {
                window.location.href =
                    "/api/commonservice/obsfile/downloadfile?objectkey=" +
                    params + '&realName=' + this.picName;
                this.picDialogVisible = false;
            } else {
                if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(params.url)) {
                    this.picDialogVisible = true;
                    this.picUrl = params.url;
                    this.picName = params.name;
                } else {
                    window.location.href =
                        "/api/commonservice/obsfile/downloadfile?objectkey=" +
                        params.url + '&realName=' + params.name;
                }
            }
        }
    },
    computed: {
      currentUser() {
        if (this.$store.state.session.user) {
          return this.$store.state.session.user;
        }
        return JSON.parse(localStorage.getItem("user"));
      },
      mockUser() {
        if (this.$store.state.session.mockUser) {
          return this.$store.state.session.mockUser;
        }
        let sessiondata = JSON.parse(localStorage.getItem("sessiondata"));
        if (sessiondata && sessiondata.mockUser) {
          return sessiondata.mockUser;
        }
      },
      //判断当前角色，处理字段权限设置
      isOperate() {
        return function(params) {
          let global = vueApp.global;
          let result = false;
          if (global.isStudent) {
            result = params.studentUpdate * 1 == 1
          } else if (global.isAcdemicDean) {
            result = params.facultyUpdate * 1 == 1
          } else if (global.isAdmin) {
            result = params.collegeUpdate * 1 == 1
          }
          return !result
        }
      }
    }
};
</script>
<style lang="scss" scoped>
.abnormal-audit {
    .title {
        font-size: 16px;
    }
    .dashed-line {
        border-bottom: 1px dashed #ccc;
        padding-bottom: 16px;
    }
    .border-form {
        border: 3px solid #ccc;
        .border-bt {
            border-bottom: 1px solid #ccc;
        }
        .border-rg {
            border-right: 1px solid #ccc;
        }
        .border-lf {
            border-left: 1px solid #ccc;
        }
        .bg {
            background-color: rgba(245, 247, 249, 1);
        }
        .pd-5px {
            padding: 0 5px;
        }
    }
}
</style>
